import { Component, Inject, Prop, Vue, Watch } from 'vue-property-decorator'
import ImgCropper from '../img-cropper/img-cropper.vue'
import Select from '../select/select.vue'
import Radio from '../radio/radio.vue'
import Cell from '../cell/cell'

@Component({ components: { ImgCropper, Select, Cell, Radio } })
export default class extends Vue {
  // ++++++++++ model ++++++++++
  // ++++++++++ props ++++++++++
  @Prop({ default: false })
  isAdd!: boolean

  @Prop({ type: Array })
  columns!: Array<IColumn>

  @Prop({ default: false })
  visible!: boolean

  @Prop()
  data!: any

  // ++++++++++ data ++++++++++
  form = {} as any

  // ++++++++++ computed ++++++++++
  @Inject('dataProvide') dataProvide!: () => any

  // ++++++++++ methods normal ++++++++++
  keyFormat(value: string) {
    return value.replace(/'/g, '')
  }

  isShowFormItem(column: IColumn, type?: TFormType) {
    if (column.isShowForm != undefined && column.isShowForm == false) {
      return false
    }

    const form = column.form

    // 没有Formyou
    if (!form) {
      return true
    }

    // passive
    const isShow = () => {
      const passive = form.passive

      if (passive) {
        const { value, key } = passive

        if (this.form[key] == value) {
          return true
        } else {
          this.form[column.key] = undefined
          return false
        }
      } else {
        return true
      }
    }

    // 有Form
    // 不允许添加
    if (form.isAdd == false) {
      return false
    }
    // 类型确定
    if (form.type == type) {
      return isShow()
    }
    // 无类型
    if (!form.type) {
      return isShow()
    }
    return false
  }

  // ++++++++++ methods event ++++++++++
  /** 关闭弹框 */
  hanldeClose() {
    this.$emit('update:visible', false)
  }

  /** 重置表单 */
  handleResetField() {
    const dataForm = this.$refs.dataForm as any

    dataForm.resetFields()
  }

  /** 提交 */
  async submit() {
    const { handleAdd, handleUpdate } = this.dataProvide()

    if (this.isAdd) {
      await handleAdd({ ...this.form })
    } else {
      await handleUpdate(this.form)
    }
    this.hanldeClose()
  }

  // ++++++++++ Lifecycle Hooks ++++++++++
  // ++++++++++ watch ++++++++++
  @Watch('visible')
  onVisibleWatch(flag: boolean) {
    const _form = {} as any

    if (!flag) {
      const form = this.$refs.dataForm as any

      form.clearValidate()
      return
    }
    if (this.columns.length == 0) {
      return
    }

    for (let i in this.columns) {
      const column = this.columns[i]
      const key = column.key

      if (column.form?.isRemove == true) {
        continue
      }

      //  Form Init
      if (this.isAdd) {
        _form[key] = column.default ?? undefined
      } else {
        _form[key] = this.data[key]
      }
    }
    if (!this.isAdd) {
      _form.id = this.data.id
    }
    this.form = { ..._form }
  }
}
